package com.momomian.common.annotation.impl;

import com.momomian.common.annotation.DateCheck;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author momomian
 * @version 1.0
 * @date 2020/10/22
 * @description 日期格式校验实现
 **/

public class DateCheckValidator  implements ConstraintValidator<DateCheck, String> {


    private String dateTimePattern;

    @Override
    public void initialize(DateCheck constraintAnnotation) {
        this.dateTimePattern = constraintAnnotation.pattern();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        DateFormat formatter = new SimpleDateFormat(dateTimePattern);
        try {
            Date date = formatter.parse(value);
            return value.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }
}
